<?php
namespace App\Http\Controllers\Admin\UsersRoles;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\UsersRolesRepository as RolesRepository;
use App\Repositories\UsersMenusRepository as menusRepository;
use App\Repositories\UsersRolesInMenusRepository as RolesInMenuRepository;
use App\Repositories\UsersRepository;
use App\Repositories\UsersInRolesRepository;
use Log;
use Storage;
use Illuminate\Support\Facades\DB;
use Exception;
/**
 * 后台角色设置
 */
class IndexController extends Controller
{

	public function __construct()
	{
	 	$this->middleware('auth:users');
	}

	/**
	 *  角色列表
	 */
	public function GetList(RolesRepository $RolesRepository, Request $request)
	{
		$pagesize = $request->input('pagesize', '25');
		$kw = $request->input('kw', '');
		$result = $RolesRepository->GetList(addslashes($kw), [], [], $pagesize, ['CreateTime' => 'desc']);
		return response()->json(['code' => 0, 'result' => $result]);
	}
	/**
	 * 创建角色
	 */
	public function Create(RolesRepository $RolesRepository, Request $request)
	{

		$model = [
			'ID' => $this->nextid(),
			'CreateTime' => time(),
			'Name' => trim($request->input('Name')),
			'Description' => trim($request->input('Description')),
			'AllowAppendMembers' => trim($request->input('AllowAppendMembers')) == '1' ? 1 : 0,
		];
		$RolesRepository->create($model);
		return response()->json(['code' => 0, 'message' => '角色创建成功！']);
	}
	/**
	 * 修改角色
	 */
	public function SetInfo(RolesRepository $RolesRepository, Request $request)
	{
		$requestData = [
			'Name' => trim($request->input('Name')),
			'Description' => trim($request->input('Description')),
			'AllowAppendMembers' => trim($request->input('AllowAppendMembers')) == '1' ? 1 : 0,
		];
		$ID = $request->input('ID');
		$RolesRepository->update($requestData, $ID);
		return response()->json(['code' => 0, 'message' => '修改成功']);
	}
	public function Enable(RolesRepository $RolesRepository, Request $request)
	{
		$ID = $request->input('ID');

		if ($RolesRepository->update(['Status' => 0], $ID)) {
			return response()->json(['code' => 0, 'message' => '启用成功']);
		}
		else {
			return response()->json(['code' => 1, 'message' => '启用失败']);
		}
	}

	public function Disable(RolesRepository $RolesRepository, Request $request)
	{
		$ID = $request->input('ID');

		if ($RolesRepository->update(['Status' => 1], $ID)) {
			return response()->json(['code' => 0, 'message' => '禁用成功']);
		}
		else {
			return response()->json(['code' => 1, 'message' => '禁用失败']);
		}
	}
	/*
	 *  删除
	 */
	public function DelItem(RolesRepository $RolesRepository, UsersInRolesRepository $UsersInRolesRepository, RolesInMenuRepository $RolesInMenuRepository, Request $request)
	{
		$ID = $request->input('ID');
		$result = $RolesRepository->findBy('ID', $ID);

		if ($result) {

			DB::beginTransaction();
			try {
				if ($result->delete()) {
					$RolesInMenuRepository->DeleteByRolesID($result->ID);
					$UsersInRolesRepository->DeleteByRolesID($result->ID);
					DB::commit();
					return response()->json(['code' => 0, 'message' => '删除成功']);
				}
			}
			catch (Exception $e) {
				DB::rollBack();
				Log::error($e->getMessage());
				return ['code' => 1, 'message' => '执行删除失败！'];
			}

		}
		else {
			return response()->json(['code' => 1, 'message' => '删除失败']);
		}
	}
	public function Tree(menusRepository $menusRepository, Request $request)
	{
		$RolesID = $request->input('ID');
		$list = $menusRepository->RolesAllByOrder(
			$RolesID,
			'Orders',
			'asc',
		['UsersMenus.ID', "UsersMenus.ParentID", "UsersMenus.Text", 'UsersMenus.Depth', 'UsersRolesInMenus.MenusID as Checked']
		);
		//Log::info($list);
		return response()->json(['code' => 0, 'result' => $list]);
	}
	public function TreeSave(RolesInMenuRepository $RolesInMenuRepository, Request $request)
	{
		$RolesID = $request->input('ID');

		$datalist = $request->input('datalist', '');
		$ids = explode(',', $datalist);
		$RolesInMenuRepository->DeleteByRolesID($RolesID);
		if (is_array($ids)) {
			foreach ($ids as $value) {

				if (!empty($value) && $value != '0') {
					$RolesInMenuRepository->create(['RolesID' => $RolesID, 'MenusID' => $value]);
				}
			}
		}
		return response()->json(['code' => 0, 'message' => '保存成功']);

	}
 
	public function GetUsersANDMembers(UsersRepository $UsersRepository, Request $request)
	{
		$RolesID = $request->input('ID');
		$result = $UsersRepository->GetUsersANDMembers($RolesID);
		return response()->json(['code' => 0, 'result' => $result]);
	}
	public function SaveMembers(UsersInRolesRepository $UsersInRolesRepository,UsersRepository $UsersRepository,RolesRepository $RolesRepository, Request $request)
	{
		$RolesID = $request->input('ID');
		$Members = $request->input('Members');
		$Users = explode(',', $Members);

		DB::beginTransaction();
		try {
			$UsersInRolesRepository->DeleteByRolesID($RolesID);
			foreach ($Users as $UsersID) {
				if ($UsersID != '') {
					$UsersInRolesRepository->create(['RolesID' => $RolesID, 'UsersID' => $UsersID]);
					$this->UpdateUserRoles($UsersID,$UsersRepository,$UsersInRolesRepository,$RolesRepository);
				}
			}
			DB::commit();
			return response()->json(['code' => 0, 'message' => '角色成员保存成功']);
		}
		catch (Exception $e) {
			DB::rollBack();
			Log::error($e->getMessage());
			return ['code' => 1, 'message' => '执行查询失败，请查看日志！'];
		}
	}
	private function UpdateUserRoles($UsersID,$UsersRepository,$UsersInRolesRepository,$RolesRepository)
	{
		$Roles=$UsersInRolesRepository->findAllBy('UsersID',$UsersID);
		 
		$model = $UsersRepository->findBy('ID', $UsersID);
		$UsersRoles=[];
			foreach ($Roles as $item) {
				$roles=$RolesRepository->find($item->RolesID);
				$UsersRoles[]=$roles->Name;
				}
		$model->Roles=join(",",$UsersRoles);
		$model->save();
	}
}
